package com.htx.zqs.blesmartmask.utils;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;

/**
 * Created by zhao on 2018/6/4.
 */

public class LocationUtil {

    private static final long  REFRESH_TIME   = 5000L;
    private static final float METER_POSITION = 0.0f;
    private static ILocationListener mLocationListener;
    private static LocationListener listener = new MyLocationListener();
    private static String city;
    private static HashMap<String, ArrayList<String>> map = new HashMap<>();

    private static class MyLocationListener implements LocationListener {
        @Override
        public void onLocationChanged(Location location) {//定位改变监听
            if (mLocationListener != null) {
                mLocationListener.onSuccessLocation(location);
            }
        }

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {//定位状态监听

        }

        @Override
        public void onProviderEnabled(String provider) {//定位状态可用监听

        }

        @Override
        public void onProviderDisabled(String provider) {//定位状态不可用监听

        }
    }

    /**
     * GPS获取定位方式
     */
    public static Location getGPSLocation(@NonNull Context context) {
        Location location = null;
        LocationManager manager = getLocationManager(context);
        //高版本的权限检查
        if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return null;
        }
        if (manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {//是否支持GPS定位
            //获取最后的GPS定位信息，如果是第一次打开，一般会拿不到定位信息，一般可以请求监听，在有效的时间范围可以获取定位信息
            location = manager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        }
        return location;
    }

    /**
     * network获取定位方式
     */
    public static Location getNetWorkLocation(Context context) {
        Location location = null;
        LocationManager manager = getLocationManager(context);
        //高版本的权限检查
        if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return null;
        }
        if (manager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {//是否支持Network定位
            //获取最后的network定位信息
            location = manager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
        }
        return location;
    }

    /**
     * 获取最好的定位方式
     */
    public static Location getBestLocation(Context context) {
        Location location;

        LocationManager manager = getLocationManager(context);
        Log.e("gps", "run: 进来没" + manager);
        Criteria c = new Criteria();//Criteria类是设置定位的标准信息（系统会根据你的要求，匹配最适合你的定位供应商），一个定位的辅助信息的类
        c.setPowerRequirement(Criteria.POWER_LOW);//设置低耗电
        c.setAltitudeRequired(true);//设置需要海拔
        c.setBearingAccuracy(Criteria.ACCURACY_COARSE);//设置COARSE精度标准
        c.setAccuracy(Criteria.ACCURACY_LOW);//设置低精度
        //... Criteria 还有其他属性，就不一一介绍了
        String provider = manager.getBestProvider(c, true);
        Log.e("gps", "run: 进来没" + provider);
        if (TextUtils.isEmpty(provider)) {
            //如果找不到最适合的定位，使用network定位
            location = getNetWorkLocation(context);
        } else {
            //高版本的权限检查
            if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED
                    && ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                Log.e("gps", "run: 权限没了吗");
                return null;
            }

            //获取最适合的定位方式的最后的定位权限
            location = manager.getLastKnownLocation(provider);
            Log.e("gps", "run: 进来没" + location);
            if (location == null) {
                location = getNetWorkLocation(context);
            }
        }
        return location;
    }

    //声明AMapLocationClient类对象
    public static AMapLocationClient   mMAPLocationClient   = null;
    //声明定位回调监听器
    public static AMapLocationListener mMAPLocationListener = new AMapLocationListener() {
        @Override
        public void onLocationChanged(AMapLocation aMapLocation) {
            if (aMapLocation != null) {
                if (aMapLocation.getErrorCode() == 0) {
                    //可在其中解析amapLocation获取相应内容。
                    addList.get(0).setCountryName(aMapLocation.getCountry());
                    addList.get(0).setAdminArea(aMapLocation.getProvince());
                    addList.get(0).setAdminArea(aMapLocation.getCity());
                    Log.e("AmapError", "location "  + aMapLocation);

                } else {
                    //定位失败时，可通过ErrCode（错误码）信息来确定失败的原因，errInfo是错误信息，详见错误码表。
                    Log.e("AmapError", "location Error, ErrCode:"
                            + aMapLocation.getErrorCode() + ", errInfo:"
                            + aMapLocation.getErrorInfo());
                }
            }
        }
    };

    public static void stopLocation() {
        mMAPLocationClient.stopLocation();
        mMAPLocationClient.onDestroy();
        addList = null;
    }

    private static List<Address> addList = null;

    public static List<Address> getLocationInfo(Location location, Context context) {
        Log.e("gps", "run: 进来没1" + "dsdsdsd");
        startLocation(context);
        Geocoder ge = new Geocoder(context);
        Log.e("gps", "run: 进来没2" + ge);

//        try {
//            addList = ge.getFromLocation(location.getLatitude(),location.getLongitude(),1);
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
        boolean present = Geocoder.isPresent();
        Log.e("gps", "run: 进来没3" + location);
        if (location != null) {
            try {
                addList = ge.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
                Log.e("gps", "run: 进来没4" + addList);
                if (addList == null){

                }
            } catch (IOException e) {
                Log.e("gps", "run: 进来没4erroe" + e);
                e.printStackTrace();
                startLocation(context);
            }

        }
        return addList;
    }

    public static void startLocation(Context context) {
        //初始化定位
        mMAPLocationClient = new AMapLocationClient(context);
        //设置定位回调监听
        mMAPLocationClient.setLocationListener(mMAPLocationListener);
        //初始化AMapLocationClientOption对象
        mLocationOption = new AMapLocationClientOption();
        //获取一次定位结果：
        //该方法默认为false。
        mLocationOption.setOnceLocation(true);
        //给定位客户端对象设置定位参数
        mMAPLocationClient.setLocationOption(mLocationOption);
//启动定位
        mMAPLocationClient.startLocation();
    }

    //声明AMapLocationClientOption对象
    public static AMapLocationClientOption mLocationOption = null;

    /**
     * 定位监听
     */
    public static void addLocationListener(Context context, String provider, ILocationListener locationListener) {

        addLocationListener(context, provider, REFRESH_TIME, METER_POSITION, locationListener);
    }

    /**
     * 定位监听
     */
    public static void addLocationListener(Context context, String provider, long time, float meter, ILocationListener locationListener) {
        if (locationListener != null) {
            mLocationListener = locationListener;
        }
        if (listener == null) {
            listener = new MyLocationListener();
        }
        LocationManager manager = getLocationManager(context);
        if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                && ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        manager.requestLocationUpdates(provider, time, meter, listener);
    }

    /**
     * 取消定位监听
     */
    public static void unRegisterListener(Context context) {
        if (listener != null) {
            LocationManager manager = getLocationManager(context);
            if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                    && ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                return;
            }
            //移除定位监听
            manager.removeUpdates(listener);
        }
    }

    public static LocationManager getLocationManager(@NonNull Context context) {
        return (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
    }

    /**
     * 自定义接口
     */
    public interface ILocationListener {
        void onSuccessLocation(Location location);
    }


    /**
     * @param ctx 上下文对象 记得添加权限android:name="android.permission.READ_PHONE_STATE"
     * @return 返回获取到的手机信息, 返回的东西太多.可以分多个函数进行写
     */
    public static String getPhoneInfo(Context ctx) {
        TelephonyManager tm = (TelephonyManager) ctx.getApplicationContext()
                .getSystemService(Context.TELEPHONY_SERVICE);
        StringBuilder sb = new StringBuilder();

        if (ActivityCompat.checkSelfPermission(ctx, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return "";
        }
        sb.append("\nDeviceID(IMEI)" + tm.getDeviceId());
        sb.append("\nDeviceSoftwareVersion:" + tm.getDeviceSoftwareVersion());
        sb.append("\ngetLine1Number:" + tm.getLine1Number());
        sb.append("\nNetworkCountryIso:" + tm.getNetworkCountryIso());
        sb.append("\nNetworkOperator:" + tm.getNetworkOperator());
        sb.append("\nNetworkOperatorName:" + tm.getNetworkOperatorName());
        sb.append("\nNetworkType:" + tm.getNetworkType());
        sb.append("\nPhoneType:" + tm.getPhoneType());
        sb.append("\nSimCountryIso:" + tm.getSimCountryIso());
        sb.append("\nSimOperator:" + tm.getSimOperator());
        sb.append("\nSimOperatorName:" + tm.getSimOperatorName());
        sb.append("\nSimSerialNumber:" + tm.getSimSerialNumber());
        sb.append("\ngetSimState:" + tm.getSimState());
        sb.append("\nSubscriberId:" + tm.getSubscriberId());
        sb.append("\nVoiceMailNumber:" + tm.getVoiceMailNumber());
        return sb.toString();
    }

    /**
     * @param ctx 上下文对象 记得添加权限android:name="android.permission.READ_PHONE_STATE"
     * @return 返回获取到的手机信息, 返回的东西太多.可以分多个函数进行写
     */
    public static TelephonyManager getPhoneInfos(Context ctx) {
        TelephonyManager tm = (TelephonyManager) ctx.getApplicationContext()
                .getSystemService(Context.TELEPHONY_SERVICE);
        StringBuilder sb = new StringBuilder();

        if (ActivityCompat.checkSelfPermission(ctx, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return null;
        }
        sb.append("\nDeviceID(IMEI)" + tm.getDeviceId());
        sb.append("\nDeviceSoftwareVersion:" + tm.getDeviceSoftwareVersion());
        sb.append("\ngetLine1Number:" + tm.getLine1Number());
        sb.append("\nNetworkCountryIso:" + tm.getNetworkCountryIso());
        sb.append("\nNetworkOperator:" + tm.getNetworkOperator());
        sb.append("\nNetworkOperatorName:" + tm.getNetworkOperatorName());
        sb.append("\nNetworkType:" + tm.getNetworkType());
        sb.append("\nPhoneType:" + tm.getPhoneType());
        sb.append("\nSimCountryIso:" + tm.getSimCountryIso());
        sb.append("\nSimOperator:" + tm.getSimOperator());
        sb.append("\nSimOperatorName:" + tm.getSimOperatorName());
        sb.append("\nSimSerialNumber:" + tm.getSimSerialNumber());
        sb.append("\ngetSimState:" + tm.getSimState());
        sb.append("\nSubscriberId:" + tm.getSubscriberId());
        sb.append("\nVoiceMailNumber:" + tm.getVoiceMailNumber());
        return tm;
    }

    public static String getUniquePsuedoID() {
        String serial = null;
        String m_szDevIDShort = "35" +
                Build.BOARD.length() % 10 + Build.BRAND.length() % 10 +
                Build.CPU_ABI.length() % 10 + Build.DEVICE.length() % 10 +
                Build.DISPLAY.length() % 10 + Build.HOST.length() % 10 +
                Build.ID.length() % 10 + Build.MANUFACTURER.length() % 10 +
                Build.MODEL.length() % 10 + Build.PRODUCT.length() % 10 +
                Build.TAGS.length() % 10 + Build.TYPE.length() % 10 +
                Build.USER.length() % 10; //13 位
        try {
            serial = android.os.Build.class.getField("SERIAL").get(null).toString();
            //API>=9 使用serial号
            return new UUID(m_szDevIDShort.hashCode(), serial.hashCode()).toString();
        } catch (Exception exception) {
            //rial需要一个初始化
            serial = "serial"; // 随便一个初始化
        }
        //使用硬件信息拼凑出来的15位号码
        return new UUID(m_szDevIDShort.hashCode(), serial.hashCode()).toString();
    }
}

